package com.wkhyapp.lm.http;


import com.wkhyapp.lm.http.net.SuperResponse;

import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

public abstract class ApiCallback<M extends SuperResponse> extends Subscriber<M> {

    public abstract void onSuccess(M model);

    public abstract void onFailure(String msg);

    public abstract void onFinish();


    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String msg;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            msg = httpException.getMessage();
//            LogUtil.d("code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg);
        } else if (InterruptedException.class.isInstance(e)) {
            msg = "连接超时";
            onFailure(msg);
        } else if (UnsupportedEncodingException.class.isInstance(e)) {
            msg = "编码错误";
            onFailure(msg);
        } else if (SocketTimeoutException.class.isInstance(e)) {
            msg = "连接超时";
            onFailure(msg);
        } else if (ConnectException.class.isInstance(e)) {
            msg = "连接超时";
            onFailure(msg);
        } else if (UnknownHostException.class.isInstance(e)) {
            msg = "当前网络不可用";
            onFailure(msg);
        } else {
            onFailure(e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onNext(M model) {

        switch (model.getCode()){
            case 200:
                onSuccess(model);
                break;
            case -1:
                onFailure(model.getMessage()+"");
                break;
            default:
                onFailure(model.getMessage()+"");
        }
    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
